<script>
// import { Editor } from '@tinymce/tinymce-vue'

import InputText from '../formComponents/input-text.vue'
import Select from '../formComponents/select.vue'
import InputFile from '../formComponents/input-file.vue'
import InputDatetime from '../formComponents/input-datetime.vue'


import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: 'TableComponent',
  components: {
    quillEditor,
    InputText,
    Select,
    InputFile,
    InputDatetime,
  },
  data() {
    return {
      content: '',
      tableData: [],
      // 单元格配置
      columns: [],
      checked: false,
      borderRadius: '0',

      //
      moduleName: this.$route.matched[0].meta.title,
      routerName: this.$route.matched[1].meta.title,
      data: [],
      dialogVisible: false,
      formModel: {},
      editingRowIndex: null,

      intervalId: null, // 用来存储定时器的 ID
    }
  },
  computed: {
    tableStyle() {
      return {
        '--table-border-radius': this.borderRadius
      }
    }
  },
  mounted() {
    this.readJsonFile()
    // 5秒后自动点击新增按钮
    setTimeout(() => {
      this.simulateAdd();
    }, 5000);
  },
  methods: {
    // 模拟点击新增按钮并自动填写表单
    simulateAdd() {
      this.openAdd(); // 模拟点击新增按钮
      let index = 0;

      // 每隔5秒填写一个表单项
      const fillFormInterval = setInterval(() => {
        if (index < this.data.length) {
          const field = this.data[index];
          this.formModel[field.enName] = `自动填写的${field.name}`; // 模拟填入数据
          index++;
        } else {
          clearInterval(fillFormInterval);

          // 最后一项填写完后，5秒后点击确定按钮
          setTimeout(() => {
            this.handleConfirm(); // 模拟点击确定按钮

            // 5秒后模拟点击编辑按钮
            setTimeout(() => {
              this.simulateEdit();
            }, 5000);
          }, 5000);
        }
      }, 5000);
    },

    // 模拟点击编辑按钮并自动修改表单
    simulateEdit() {
      const firstRow = this.tableData[0]; // 假设编辑第一行
      this.editRowInfo(firstRow, 0); // 模拟点击编辑按钮

      let index = 0;

      // 每隔5秒修改一个表单项
      const editFormInterval = setInterval(() => {
        if (index < this.data.length) {
          const field = this.data[index];
          this.formModel[field.enName] = `修改后的${field.name}`; // 模拟修改数据
          index++;
        } else {
          clearInterval(editFormInterval);

          // 最后一项修改完后，5秒后点击确定按钮
          setTimeout(() => {
            this.handleConfirm(); // 模拟点击确定按钮
          }, 5000);
        }
      }, 5000);
    },

















    // 读取json文件
    readJsonFile() {
      // console.log(this.moduleName, 'this.moduleName==============>')
      // console.log(this.routerName, 'this.routerName==============>')
      if (this.$store.state.config.configData.projectJson.modules) {
        const modules = this.$store.state.config.configData.projectJson.modules
        // console.log(modules,'==================>',this.moduleName)
        //筛选modules中moduleName===this.moduleName的
        const moduleData = modules.filter(item => item.moduleName.replace("模块", "") === this.moduleName)
        // const moduleData = modules.filter(item => item.moduleName === this.moduleName)
        // console.log(moduleData,'moduleData')
        moduleData[0].tables.map(item => {
          //找在item中=tableEnName == this.routerName的
          if (item.tableName.replace("表0", "") === this.routerName) {
            this.data = item.columns
          }
        })

        // console.log(this.data,'this.data')


        this.data.map(item => {
          this.columns.push({
            name: item.name,
            enName: item.enName
          })
          this.tableData.push({
            [item.enName]: item.mockDataList
          })
        })
        // console.log(this.tableData,'this.tableData')

        // 动态提取键名
        const keys = this.tableData.map(obj =>  Object.keys(obj)[0]);
        // console.log(keys,)
        // 使用 map 遍历第一个数组的内容（例如 modelId 数组），按索引组合数据
        const result = this.tableData[0][keys[0]].map((_, index) => {
          let obj = {};  // 创建一个空对象用于存储每个模型的数据
          keys.forEach((key, i) => {
            obj[key] = this.tableData[i][key][index];  // 按照顺序将各个字段的数据加入对象中
          });
          return obj;  // 返回每个组合后的对象
        });
        // console.log(result,'result')

        this.tableData = result
      }
    },
    // 根据 viewControlType 返回组件名称
    getComponentName(viewControlType) {
      const componentMap = {
        'input-text': 'InputText',
        'select': 'Select',
        'input-file': 'InputFile',
        'input-datetime': 'InputDatetime',
      }
      return componentMap[viewControlType] || 'InputText'
    },
    checkboxChange(val) {
      if (val) {
        this.borderRadius = '20px'
      } else { this.borderRadius = '0px' }
    },
    openAdd() {
      this.formModel = {}
      this.editingRowIndex = null;  // 记录正在新增的行的索引
      this.data.forEach(field => {
        this.$set(this.formModel, field.enName, ''); // 为每个字段初始化空字符串
      });
      this.dialogVisible = true
    },
    //编辑行
    editRowInfo(row,index) {
      console.log(row)
      this.formModel = { ...row };  // 克隆一份数据用于编辑
      this.editingRowIndex = index;  // 记录正在编辑的行的索引
      this.dialogVisible = true
      this.formModel = row
    },
    handleConfirm() {
      if (this.editingRowIndex !== null) {
        // 更新表格数据
        this.updateTableContent(this.formModel, this.editingRowIndex);
      } else {
        // 新增操作逻辑
        this.tableData.push({ ...this.formModel });
      }

      console.log(this.tableData,this.formModel)
      // 关闭弹窗
      this.dialogVisible = false;
    },

    updateTableContent(formModel, index) {
      // 使用编辑后的 formModel 替换对应索引的数据
      this.$set(this.tableData, index, { ...formModel });
      console.log('更新表格内容:', this.tableData[index]);
    },
    deleteRowInfo(index) {
      this.tableData.splice(index, 1);
    }
  }
}
</script>

<template>
  <div>
    <el-card style="margin-bottom: 30px">
      <el-button @click="openAdd">新增</el-button>
      <el-checkbox v-model="checked" @change="checkboxChange">是否为圆角边框</el-checkbox>
    </el-card>

    <!--自定义表头的表格-->
    <el-card>
      <el-table :style="tableStyle" class="drawer-item" :data="tableData" style="width: 100%" border>
        <el-table-column
          v-for="column in columns"
          :key="column.enName"
          :prop="column.enName"
          :label="column.name"
        />

        <template>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="editRowInfo(scope.row,scope.$index)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteRowInfo(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </template>
      </el-table>

    </el-card>

    <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="60%"
    >
      <el-form :model="formModel" label-width="150px">
        <el-form-item
          v-for="(field, index) in data"
          :key="index"
          :label="field.name + ':'"
        >
          <component
            :is="getComponentName(field.viewControlType)"
            v-model="formModel[field.enName]"
            :placeholder="'请输入' + field.name"
            :options="field.mockDataList"
          />
        </el-form-item>
      </el-form>


<!--      <quill-editor v-model="content" />-->
      <!--      <Editor-->
      <!--        v-model="content"-->
      <!--        :init="{-->
      <!--        height: 500,-->
      <!--        menubar: false,-->
      <!--        plugins: 'link image table',-->
      <!--        toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright | link image | table',-->
      <!--      }"-->
      <!--      />-->

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">

::v-deep {
  .el-table--enable-row-transition .el-table__body td  {
    border-radius: var(--table-border-radius);
  }
  .el-table th.is-leaf, .el-table td {
    border-radius:  var(--table-border-radius);
  }
  .el-table--border {
    border-radius:  var(--table-border-radius);
  }

}
</style>
